// hooks/useScrollPosition.ts
import { ref, onActivated, onDeactivated, onMounted, onUnmounted, nextTick } from 'vue'

interface UseScrollPositionOptions {
  containerSelector?: string // 容器选择器，默认为 document
  debounceTime?: number // 防抖时间，默认0ms
}

export function useScrollPosition(options: UseScrollPositionOptions = {}) {
  const { containerSelector = '', debounceTime = 0 } = options

  const scrollPosition = ref(0)
  const container = ref<HTMLElement | Window | null>(null)

  // 获取容器元素
  const getContainer = () => {
    if (containerSelector) {
      return document.querySelector(containerSelector) as HTMLElement
    }
    return window
  }

  // 防抖函数
  const debounce = (fn: () => void, delay: number) => {
    let timer: number | null = null
    return () => {
      if (timer) clearTimeout(timer)
      timer = setTimeout(fn, delay) as unknown as number
    }
  }

  // 处理滚动事件
  const handleScroll = debounce(() => {
    if (container.value === window) {
      scrollPosition.value = window.scrollY
    } else if (container.value) {
      scrollPosition.value = (container.value as HTMLElement).scrollTop
    }
  }, debounceTime)

  // 恢复滚动位置
  const restoreScrollPosition = () => {
    if (container.value === window) {
      window.scrollTo({ top: scrollPosition.value })
    } else if (container.value) {
      ;(container.value as HTMLElement).scrollTop = scrollPosition.value
    }
  }

  onMounted(() => {
    container.value = getContainer()
    if (container.value === window) {
      window.addEventListener('scroll', handleScroll)
    } else if (container.value) {
      ;(container.value as HTMLElement).addEventListener('scroll', handleScroll)
    }
  })

  onActivated(() => {
    nextTick(() => {
      setTimeout(restoreScrollPosition, 0)
    })
  })

  onDeactivated(() => {
    handleScroll() // 确保在缓存前记录最新位置
  })

  onUnmounted(() => {
    if (container.value === window) {
      window.removeEventListener('scroll', handleScroll)
    } else if (container.value) {
      ;(container.value as HTMLElement).removeEventListener('scroll', handleScroll)
    }
  })

  return {
    scrollPosition,
  }
}
